package com.will.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.will.common.constant.HttpStatus;
import com.will.common.dto.AccountDto;
import com.will.common.dto.OrderDto;
import com.will.common.response.AjaxResult;
import com.will.order.convert.OrderConvert;
import com.will.order.domain.Order;
import com.will.order.mapper.OrderMapper;
import com.will.order.service.IAccountService;
import com.will.order.service.IOrderService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private IAccountService accountService;

    @Autowired
    private OrderConvert orderConvert;

    @Override
    public AjaxResult createOrder(OrderDto orderDto) {
        try {
            AccountDto accountDto = new AccountDto();
            accountDto.setUserId(orderDto.getUserId());
            accountDto.setBalance(orderDto.getOrderAmount());
            AjaxResult accountAjaxResult = accountService.decreaseAccount(accountDto);
            Order order = orderConvert.dto2Order(orderDto);
            order.setOrderNo(UUID.randomUUID().toString());
            if (!Integer.valueOf(accountAjaxResult.get("code").toString()).equals(HttpStatus.SUCCESS)) {
                return AjaxResult.error(accountAjaxResult.get("msg").toString());
            }
            this.save(order);
            return AjaxResult.success();
        } catch (NumberFormatException e) {
            return AjaxResult.error();
        }
    }
}
